<template>
  <p class="form-row-title">分类区域</p>
  <tree-swipe-cell
    v-model:data="roles"
    :option="{ label: 'cg_name', label2: 'cg_uuid', children: 'children' }"
  >
    <template v-slot="{ scope }">
      <van-button square type="primary" text="编辑" />
      <van-button
        square
        type="danger"
        text="删除"
        @click="deleteCategory(scope.item.cg_uuid)"
      />
    </template>
  </tree-swipe-cell>
  <p class="margin-5"></p>
  <!-- 分页器 -->
  <van-pagination
    v-model="page"
    :total-items="count"
    :items-per-page="size"
    :show-page-size="4"
    @change="pageChange"
  />
  <p class="margin-5"></p>
  <!-- 新建分类按钮 -->
  <van-button type="primary" size="large" block @click="addCategoryShow = true"
    >新建分类</van-button
  >
  <!-- 弹出框 添加用户 -->
  <van-dialog
    v-model:show="addCategoryShow"
    title="添加分类"
    :show-confirm-button="false"
  >
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
          v-model="name"
          name="name"
          label="分类名"
          placeholder="分类名"
          :rules="[{ required: true, message: '请填写分类名' }]"
        />
        <van-field
          v-model="pidName"
          is-link
          readonly
          label="上级分类"
          placeholder="请选择上级分类"
          @click="previouCategoryShow = true"
        />
        <van-popup v-model:show="previouCategoryShow" round position="bottom">
          <van-cascader
            v-model="pid"
            title="请选择上级分类"
            :options="options"
            @close="previouCategoryShow = false"
            @change="onChange"
            @finish="onFinish"
            :field-names="fieldNames"
          />
        </van-popup>
      </van-cell-group>
      <div style="margin: 16px">
        <van-row>
          <van-col :span="11">
            <van-button
              round
              block
              plain
              type="primary"
              @click="addCategoryShow = false"
              >取消添加</van-button
            >
          </van-col>
          <van-col :span="11" :offset="2">
            <van-button
              round
              block
              type="primary"
              native-type="submit"
              @click="handleraddCategory"
            >
              添加分类
            </van-button>
          </van-col>
        </van-row>
      </div>
    </van-form>
  </van-dialog>
</template>
  
<script setup>
import { ref, onMounted, getCurrentInstance } from "vue";
import { Tools } from "../../utils/Tools";
import TreeSwipeCell from "../../components/treeSwipeCell/TreeSwipeCell.vue";
const count = ref(0);
const page = ref(1);
const size = ref(10);
const name = ref("");
const roles = ref([]);
const addCategoryShow = ref(false);
const { proxy } = getCurrentInstance();
const previouCategoryShow = ref(false);
const pid = ref(0);
const pidName = ref("");
const options = ref(null);
const fieldNames = {
  text: "cg_name",
  value: "cg_uuid",
};
function onSubmit() {}
function onChange({ selectedOptions, value }) {
  if (selectedOptions[selectedOptions.length - 1].hasChildren) {
    proxy.$AllRequest
      .getCategories(
        1,
        99999999,
        selectedOptions[selectedOptions.length - 1].cg_uuid
      )
      .then((res) => {
        if (res.data.code == 2000) {
          selectedOptions[selectedOptions.length - 1]["children"] =
          [{
              cg_name: selectedOptions[selectedOptions.length - 1].cg_name,
              cg_uuid: selectedOptions[selectedOptions.length - 1].cg_uuid,
            }].concat(res.data.data);
        } else {
          Tools.showMessage("获取子分类失败!" + res.data.msg, "danger");
        }
      });
  }
}
function onFinish({ selectedOptions }) {
  previouCategoryShow.value = false;
  pidName.value = selectedOptions[selectedOptions.length - 1].cg_name;
}
function getAllCategories() {
  proxy.$AllRequest.getCategories(1, 99999999).then((res) => {
    if (res.data.code == 2000) {
      options.value = [
        {
          cg_name: "顶级分类",
          cg_uuid: "0",
          hasChildren: false,
        },
      ].concat(res.data.data);
    } else {
      Tools.showMessage("获取分类失败!" + res.data.msg, "danger");
    }
  });
}
async function getCategories() {
  return await proxy.$AllRequest
    .getCategories(page.value, size.value)
    .then((res) => {
      if (res.data.code == 2000) {
        count.value = res.data.count;
        roles.value = getData(res.data.data);
      } else {
        Tools.showMessage("获取分类失败!" + res.data.msg, "danger");
      }
    });
}
async function getChildrenCategories(_pid) {
  return await proxy.$AllRequest
    .getCategories(1, 99999999, _pid)
    .then((res) => res.data.data);
}

function getData(_data = []) {
  let result = _data.map((item) => {
    if (item.hasChildren) {
      getChildrenCategories(item.cg_uuid).then((res) => {
        item.children = res;
        item.actived = false;
        if (item.children.some((item) => item.hasChildren)) {
          getData(item.children);
        }
      });
    }
    return item;
  });

  return result;
}

function handleraddCategory() {
  proxy.$AllRequest
    .addCategory({ name: name.value, pid: pid.value })
    .then((res) => {
      if (res.data.code == 2000) {
        Tools.showMessage("添加成功!");
        addCategoryShow.value = false;
        getCategories();
        getAllCategories();
      } else {
        Tools.showMessage(res.data.msg, "warning");
      }
    });
}
function deleteCategory(uuid) {
  proxy.$Dialog
    .confirm({
      title: "提示",
      message: "可能会出现未知的错误,确定要删除这个分类吗?",
    })
    .then(() => {
      proxy.$AllRequest.deleteCategory({ uuid }).then((res) => {
        if (res.data.code == 2000) {
          Tools.showMessage("删除成功!");
          addCategoryShow.value = false;
          getCategories();
          getAllCategories();
        } else {
          Tools.showMessage(res.data.msg, "warning");
        }
      });
    });
}
function pageChange(_newPage) {
  page.value = _newPage;
  getCategories();
}

onMounted(() => {
  getCategories();
  getAllCategories();
});
</script>

<style scoped>
</style>
